<template>
  <PageContainer>
    <!-- 搜索框 -->
    <el-form :inline="true">
      <el-form-item label="名字">
        <el-input v-model="searchForm.name" clearable @change="getTableData" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="openDialog('0')">新增</el-button>
        <el-button type="primary" @click="exportFile">导出</el-button>
        <el-button type="primary" @click="importFile">导入</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="useChildRef">调用子组件</el-button>
      </el-form-item>
    </el-form>

    <PageTable
      :data="tableData"
      :align="'center'"
      show-overflow-tooltip
      :pagination="pagination"
      :loading="loading"
    >
      <el-table-column type="index" label="No" />
      <el-table-column prop="username" label="账号" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="sex" label="性别">
        <template #default="{ row }">
          <span v-if="row.sex == '1'">男</span>
          <span v-if="row.sex == '0'">女</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <span v-if="row.status === 1">启用</span>
          <span v-if="row.status === 0">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="idNumber" label="身份证号" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openDialog('1', row)">编辑</el-button>
        </template>
      </el-table-column>
    </PageTable>
  </PageContainer>

  <!-- 新增、编辑用户的弹窗 -->
  <AddOrEditDialog
    ref="childRef"
    :currentUser="currentUser"
    :dialogTitle="dialogTitle"
    :dialogType="dialogType"
    v-model:visible="dialogVisible"
    @submit="handleFormSubmit"
  />

  <!-- 导入员工列表-->
  <custom-import
    v-model:visible="importVisible"
    :title="'导入设备列表'"
    @success="importSuccess"
    :importApi="uploadUserExcel"
    :downloadUrl="'/downLoadFile/template/员工表模板.xlsx'"
    fileName="importUser.xlsx"
  />
</template>

<script setup lang="ts">
import { useTable } from '@/hooks/usePage'
import { getEmployeeListReq, addEmployeeReq, editEmployeeReq } from '@/api/employee/index'
import AddOrEditDialog from './components/addOrEditDialog.vue'
import { User } from './config/constant'
import { ElMessage } from 'element-plus'
import { useExport } from '@/hooks/useExport'
import CustomImport from '@/components/common/CustomImport.vue'
import { RequestEnum } from '@/enums/httpEnum'
import request from '@/utils/requests'
// import emitter from '@/utils/eventBus'
import { eventBus } from '@/utils/myEventBus'

const route = useRoute()
onMounted(() => {})

const searchForm = reactive({
  name: ''
})

const { loading, tableData, getTableData, pagination, refreshTable } = useTable(
  (p) => getEmployeeListReq({ ...p, name: searchForm.name }),
  {
    immediate: true,
    formatResult: (data) => {
      return data
    }
  }
)

const dialogVisible = ref(false)
const currentUser = ref<any>({})
//'0'：新增 '1'编辑 '2'仅查看
const dialogType = ref('0')
const dialogTitle = ref('')
// 打开新增或编辑用户弹窗
const openDialog = (type: string, row?: any) => {
  currentUser.value = row ? { ...row } : {}
  dialogTitle.value = type === '1' ? '编辑用户' : '新增用户'
  dialogType.value = type
  dialogVisible.value = true
}

// 父组件监听子组件的确定按钮。确定新增/确定编辑
const handleFormSubmit = async (user: User, type: string) => {
  console.log('提交新增编辑', user, type)

  if (type === '0') {
    const res = await addEmployeeReq(user)
    if (res.code === 1) {
      ElMessage.success('新增用户成功')
      getTableData() // 刷新列表
    }
  } else if (type === '1') {
    const res = await editEmployeeReq(user)
    if (res.code === 1) {
      ElMessage.success('编辑用户成功')
      getTableData() // 刷新列表
    }
  }
}

// 父传子：父组件主动更改子组件的状态
const childRef = ref()
const useChildRef = () => {
  // 调用子组件 defineExpose 暴露的状态数据
  const value = childRef.value?.getFormValue()
  // 调用子组件 defineExpose 暴露的方法
  childRef.value?.handleClose()
}

// 导出
const exportFile = () => {
  // java 的静态资源导出
  // 导出30天运营数据
  // useExport('/admin/report/export', '30天运营数据.xlsx', {}, 'GET')

  // 导出员工列表
  useExport('/admin/employee/export', '员工列表数据.xlsx', {}, 'GET')
}

const importVisible = ref(false)
// 导入
const importFile = () => {
  importVisible.value = true
}

// 导入成功后的回调函数
const importSuccess = () => {
  // emitter.emit('refreshEmployee')
  eventBus.emit('refreshEmployee')
  importVisible.value = false

  getTableData() //刷新
}

// 导入 api
const uploadUserExcel = async (data: any) => {
  return await request.request(
    {
      headers: { 'Content-Type': 'multipart/form-data' },
      method: RequestEnum.POST,
      url: '/admin/employee/importEmployeeExcel',
      data
    },
    { timeout: 60 * 1000 * 30 }
  )
}
</script>
